package com.dong.aoptools.premain;

import com.dong.aoptools.constant.PropertiesConst;
import com.dong.aoptools.premain.handler.AOPHandler;
import com.dong.aoptools.premain.handler.CommonHandler;
import com.dong.aoptools.premain.handler.OutputLoadedClassHandler;
import com.dong.aoptools.util.PropertiesUtils;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.LinkedHashMap;
import java.util.Map;

public class ProfilingTransformer implements ClassFileTransformer {

    // 配置处理映射
    public Map<String, CommonHandler> handlerMap = PropertiesConst.HANDLER_KEY_VALUE;

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        try {
            // 获取配置的扫描包
            String activeHandler = PropertiesUtils.getConfigProperty(PropertiesConst.CONFIG_FIELD_HANDLER_ACTIVE, PropertiesConst.TYPE_AOP);
            CommonHandler handler = handlerMap.getOrDefault(activeHandler, new AOPHandler());
            return handler.doHandler(loader, className, classfileBuffer);
        } catch (Throwable e) {
            System.out.println("======================");
            System.out.println(className);
            System.out.println(e);
            System.out.println("======================");
            return classfileBuffer;
        }
    }

}